var express = require("express");
var router = express.Router();
var path = require("path");
var fs = require("fs");
const multer = require("multer");

var { SystemParams } = require(path.join(process.cwd(), "/models.js"));

router.post(
  "/upload",
  multer({
    dest: "uploads/imgs",
  }).single("file"),
  function (req, res, next) {
    const file = req.file;
    const type = file.originalname.split(".");
    const newPath = file.path + "." + type.pop();
    fs.renameSync(file.path, newPath);
    res.sendResult({ path: newPath }, 0, "上传成功");
  }
);

router.post(
  "/upload/files",
  multer({
    dest: "uploads/files",
  }).single("file"),
  function (req, res, next) {
    const file = req.file;
    const type = file.originalname.split(".");
    const newPath = file.path + "." + type.pop();
    fs.renameSync(file.path, newPath);
    res.sendResult({ path: newPath }, 0, "上传成功");
  }
);

router.post("/download", function (req, res) {
  const { user } = req.query;
  let { file_url, articleId } = req.body;
  if (user && user.downloads) {
    const articleIds = user.downloads.split(",");
    if (articleIds.includes(articleId + "")) {
      // The must headers.
      res.setHeader("Content-type", "application/octet-stream");
      res.setHeader("Content-Disposition", "attachment;filename=aaa.txt"); // 'aaa.txt' can be customized.
      var fileStream = fs.createReadStream(file_url);
      fileStream.on("data", function (data) {
        res.write(data, "binary");
      });
      fileStream.on("end", function () {
        return res.end();
      });
    } else {
      return res.sendResult(null, 1, "你没有下载权限");
    }
  } else {
    return res.sendResult(null, 1, "你没有下载权限");
  }
});

// 获取系统参数接口
router.get("/getSystemParams", async function (req, res, next) {
  let params = {};
  try {
    params = await SystemParams.findAll();
    return res.sendResult(params, 0, "获取系统参数成功");
  } catch (error) {
    return res.sendResult(params, 0, "获取系统参数失败");
  }
});

module.exports = router;
